package top.italks.camera;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.Manifest.permission;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewOutlineProvider;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.google.gson.Gson;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.MediaType;

public class MainActivity extends AppCompatActivity implements SurfaceTextureListener {

    private ScanView2 scanView;
    private Camera c;
    private SurfaceHolder surfaceHolder;
    private TextureView textureView;
    private RelativeLayout takeCamera;
    private RelativeLayout cycle1;
    private RelativeLayout cycle2;
    private LinearLayout word1Layout;
    private LinearLayout word2Layout;
    private RelativeLayout word3Layout;
    private LinearLayout word4Layout;
    private LinearLayout word5Layout;
    private RelativeLayout word6Layout;
    private RelativeLayout starkSpeakLayout;
    private TextView word1;
    private TextView word2;
    private TextView word3;
    private TextView word4;
    private TextView word5;
    private TextView word6;
    private TextView beautyComment;
    private TextView starkSpeak;
    private ImageView takePng;
    private ImageView similarFace;
    private ImageView preview;
    private TextView takeText;
    private TextView simiDegree;
    private boolean isTake = false;
    private KProgressHUD kProgressHUD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scanView = (ScanView2) findViewById(R.id.scanview2);
        textureView = (TextureView) findViewById(R.id.textureView);
        textureView.setSurfaceTextureListener(this);
        takeCamera = (RelativeLayout) findViewById(R.id.takeCamera);
        cycle1 = (RelativeLayout) findViewById(R.id.cycle1);
        cycle2 = (RelativeLayout) findViewById(R.id.cycle2);
        takePng = (ImageView) findViewById(R.id.takePng);
        similarFace = (ImageView) findViewById(R.id.similarFace);
        preview = (ImageView) findViewById(R.id.preview);
        takeText = (TextView) findViewById(R.id.takeText);
        simiDegree = (TextView) findViewById(R.id.simiDegree);
        word1 = (TextView) findViewById(R.id.word1);
        word2 = (TextView) findViewById(R.id.word2);
        word3 = (TextView) findViewById(R.id.word3);
        word4 = (TextView) findViewById(R.id.word4);
        word5 = (TextView) findViewById(R.id.word5);
        word6 = (TextView) findViewById(R.id.word6);
        beautyComment = (TextView) findViewById(R.id.beautyComment);
        starkSpeak = (TextView) findViewById(R.id.starkSpeak);
        word1Layout = (LinearLayout) findViewById(R.id.word1Layout);
        word2Layout = (LinearLayout) findViewById(R.id.word2Layout);
        word3Layout = (RelativeLayout) findViewById(R.id.word3Layout);
        word4Layout = (LinearLayout) findViewById(R.id.word4Layout);
        word5Layout = (LinearLayout) findViewById(R.id.word5Layout);
        word6Layout = (RelativeLayout) findViewById(R.id.word6Layout);
        starkSpeakLayout = (RelativeLayout) findViewById(R.id.starkSpeakLayout);
        kProgressHUD = KProgressHUD.create(MainActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f);
        takeCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(MainActivity.this,"返回"+isTake,Toast.LENGTH_SHORT).show();
                if (!isTake) {
                    isTake = true;
                    takeCamera();
                    kProgressHUD.show();
                } else {
                    preview.setVisibility(View.INVISIBLE);
                    word1Layout.setVisibility(View.INVISIBLE);
                    word2Layout.setVisibility(View.INVISIBLE);
                    word3Layout.setVisibility(View.INVISIBLE);
                    word4Layout.setVisibility(View.INVISIBLE);
                    word5Layout.setVisibility(View.INVISIBLE);
                    word6Layout.setVisibility(View.INVISIBLE);
                    beautyComment.setVisibility(View.INVISIBLE);
                    starkSpeakLayout.setVisibility(View.INVISIBLE);
                    scanView.setVisibility(View.VISIBLE);
                    isTake = false;
                    takeText.setText("测颜值");
                    takePng.setBackgroundResource(R.mipmap.camera);
//                    c.startPreview();
                }
            }
        });
        initPermi();
        startAnim();
        textureView.setOutlineProvider(new CircleViewOutlineProvider());
        textureView.setClipToOutline(true);


    }

    public Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        Bitmap resizedBitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
//            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            // 创建新的图片
            resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resizedBitmap;
    }

    private void startAnim() {
        Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.cycle2_anim);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        cycle1.startAnimation(operatingAnim);
//        cycle2.startAnimation(operatingAnim);
    }

    private void initPermi() {
        ActivityCompat.requestPermissions(this,
                new String[]{permission.CAMERA, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}
                , 40);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    private void closeCamera() {
        c.setPreviewCallback(null);
        c.stopPreview();
        c.release();
        c = null;
    }

    private void upload(String base64) {
        HashMap<String, String> map = new HashMap<>();
        map.put("imageBase64", base64);
        OkHttpUtils
                .postString()
                .url("http://150.158.182.100:8086/front/getFace")
                .content(new Gson().toJson(map))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        kProgressHUD.dismiss();
                        Toast.makeText(MainActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        takeText.setText("返回");
                        takePng.setBackgroundResource(R.mipmap.back);
                        kProgressHUD.dismiss();
                        Result result = new Gson().fromJson(response, Result.class);
                        if (result.getCode() == 200) {
                            starkSpeakLayout.setVisibility(View.VISIBLE);
                            Glide.with(MainActivity.this)
                                .load(stringToBitmap(result.getData().getSimilarFace()))
//                                .transform(new MultiTransformation<Bitmap>(new CircleCrop(),new Rotate(270)))
                                .transform(new CircleCrop()) // 数字根据自己需求来改
                                .into(similarFace);

                            beautyComment.setVisibility(View.VISIBLE);
                            starkSpeak.setVisibility(View.VISIBLE);
                            simiDegree.setText("相似度" + result.getData().getSimiDegree());
                            beautyComment.setText(result.getData().getBeautyComment());
                            starkSpeak.setText(result.getData().getStarSpeak());
                            switch (result.getData().getFaceComments().size()) {
                                case 1:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.INVISIBLE);
                                    word3Layout.setVisibility(View.INVISIBLE);
                                    word4Layout.setVisibility(View.INVISIBLE);
                                    word5Layout.setVisibility(View.INVISIBLE);
                                    word6Layout.setVisibility(View.INVISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    break;
                                case 2:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.VISIBLE);
                                    word3Layout.setVisibility(View.INVISIBLE);
                                    word4Layout.setVisibility(View.INVISIBLE);
                                    word5Layout.setVisibility(View.INVISIBLE);
                                    word6Layout.setVisibility(View.INVISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    word2.setText(result.getData().getFaceComments().get(1));
                                    break;
                                case 3:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.VISIBLE);
                                    word3Layout.setVisibility(View.VISIBLE);
                                    word4Layout.setVisibility(View.INVISIBLE);
                                    word5Layout.setVisibility(View.INVISIBLE);
                                    word6Layout.setVisibility(View.INVISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    word2.setText(result.getData().getFaceComments().get(1));
                                    word3.setText(result.getData().getFaceComments().get(2));
                                    break;
                                case 4:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.VISIBLE);
                                    word3Layout.setVisibility(View.VISIBLE);
                                    word4Layout.setVisibility(View.VISIBLE);
                                    word5Layout.setVisibility(View.INVISIBLE);
                                    word6Layout.setVisibility(View.INVISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    word2.setText(result.getData().getFaceComments().get(1));
                                    word3.setText(result.getData().getFaceComments().get(2));
                                    word4.setText(result.getData().getFaceComments().get(3));
                                    break;
                                case 5:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.VISIBLE);
                                    word3Layout.setVisibility(View.VISIBLE);
                                    word4Layout.setVisibility(View.VISIBLE);
                                    word5Layout.setVisibility(View.VISIBLE);
                                    word6Layout.setVisibility(View.INVISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    word2.setText(result.getData().getFaceComments().get(1));
                                    word3.setText(result.getData().getFaceComments().get(2));
                                    word4.setText(result.getData().getFaceComments().get(3));
                                    word5.setText(result.getData().getFaceComments().get(4));
                                    break;
                                case 6:
                                    word1Layout.setVisibility(View.VISIBLE);
                                    word2Layout.setVisibility(View.VISIBLE);
                                    word3Layout.setVisibility(View.VISIBLE);
                                    word4Layout.setVisibility(View.VISIBLE);
                                    word5Layout.setVisibility(View.VISIBLE);
                                    word6Layout.setVisibility(View.VISIBLE);
                                    word1.setText(result.getData().getFaceComments().get(0));
                                    word2.setText(result.getData().getFaceComments().get(1));
                                    word3.setText(result.getData().getFaceComments().get(2));
                                    word4.setText(result.getData().getFaceComments().get(3));
                                    word5.setText(result.getData().getFaceComments().get(4));
                                    word6.setText(result.getData().getFaceComments().get(5));
                                    break;
                            }
                        } else if (result.getCode() == 500) {
                            Toast.makeText(MainActivity.this, "系统繁忙", Toast.LENGTH_LONG).show();
                        } else if (result.getCode() == 222203) {
                            Toast.makeText(MainActivity.this, "未检测到人脸", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void takeCamera() {
        c.takePicture(new ShutterCallback() {
            @Override
            public void onShutter() {

            }
        }, new PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Log.e("TAG", "");
            }
        }, new PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Log.e("TAG", "");
//                camera.stopPreview();
//                scanView.setState(ScanView2.STATE_SUCCESS);
                scanView.setVisibility(View.INVISIBLE);
                upload(Base64.encodeToString(data, Base64.DEFAULT));

                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                preview.setVisibility(View.VISIBLE);

                Glide.with(MainActivity.this)
                    .load(bitmap)
                    .transform(new CircleCrop()) // 数字根据自己需求来改
                    .into(preview);

            }
        });
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        try {
            c = Camera.open(1);
            Camera.Size previewSize = c.getParameters().getPreviewSize();
//            textureView.setLayoutParams(
//                new RelativeLayout.LayoutParams(previewSize.width, previewSize.height));
            try {
                c.setPreviewTexture(surface);
            } catch (IOException t) {
            }
            c.startPreview();
            textureView.setAlpha(1.0f);
            textureView.setScaleX(-1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        c.stopPreview();
        c.release();
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

    public static class CircleViewOutlineProvider extends ViewOutlineProvider {

        public CircleViewOutlineProvider() {

        }

        @Override

        public void getOutline(View view, Outline outline) {
//864,648  横屏情况下，宽>高
            Log.d("Circle===", "width:" + view.getWidth() + "==height:" + view.getHeight());
//裁剪成一个圆形
            int left0 = (view.getWidth() - view.getHeight()) / 2;
            int top0 = 0;
            int right0 = left0 + view.getHeight();
            int bottom0 = view.getHeight();
            outline.setOval(left0, top0, right0, bottom0);
        }

    }
}